using AutoMapper;
using B.S.NewMedical.Api.Write.Application.Command.ContentManagement.Department;
using B.S.NewMedical.Domain.Doctor;
using B.S.NewMedical.Infrastructure.Interface;
using MediatR;
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace B.S.NewMedical.Api.Write.Application.Handler.ContentManagement.Department
{
    /// <summary>
    /// 新增科室命令处理器
    /// </summary>
    public class AddDepartmentCommandHandler : IRequestHandler<AddDepartmentCommand, int>
    {
        private readonly IMapper _mapper;
        private readonly IBaseRepository<DepartmentModel> _departmentRepository;

        public AddDepartmentCommandHandler(IMapper mapper, IBaseRepository<DepartmentModel> departmentRepository)
        {
            _mapper = mapper ?? throw new ArgumentNullException(nameof(mapper));
            _departmentRepository = departmentRepository ?? throw new ArgumentNullException(nameof(departmentRepository));
        }

        /// <summary>
        /// 处理新增科室命令
        /// </summary>
        /// <param name="request">新增科室命令</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>新增的科室ID</returns>
        public async Task<int> Handle(AddDepartmentCommand request, CancellationToken cancellationToken)
        {
            // 如果是二级科室，验证父级科室是否存在
            if (request.ParetId > 0)
            {
                var parentDepartment = await _departmentRepository.GetValue(request.ParetId);
                if (parentDepartment == null || parentDepartment.IsDeleted)
                {
                    throw new ArgumentException("父级科室不存在或已被删除");
                }

                // 验证父级科室确实是一级科室
                if (parentDepartment.ParetId != 0)
                {
                    throw new ArgumentException("只能在一级科室下创建二级科室");
                }
            }

            // 检查科室名称是否重复（同一父级下不能有相同名称的科室）
            var existingDepartments = _departmentRepository.GetAll()
                .Where(d => d.ParetId == request.ParetId && 
                           d.DepartmentName == request.DepartmentName && 
                           !d.IsDeleted)
                .ToList();

            if (existingDepartments.Any())
            {
                throw new ArgumentException($"在{(request.ParetId == 0 ? "一级科室" : "该父级科室")}下已存在名称为'{request.DepartmentName}'的科室");
            }

            // 使用 AutoMapper 将命令映射为实体
            var departmentEntity = _mapper.Map<DepartmentModel>(request);

            // 设置创建时间
            departmentEntity.CreateTime = DateTime.Now;

            // 调用仓储层保存数据
            await _departmentRepository.CreateAsync(departmentEntity);
            return departmentEntity.Id;
        }
    }
}